<?php
class Zendvn_Model_Table_Group extends Zendvn_Model_Nested{
	protected $_name = 'user_group';
	protected $_id = 'id';
	
	public $_alias = 'node';
	
	public $_searchFields = array('name'=>'- Name field','code'=>'- Code field');
	
	protected $_listSQL;

	public function getExtGroup($user_id,$part = null, $options = null){
		$db = $this->getAdapter();
		
		$defaultGroupID = $this->getDefaultGroup($user_id,'id');
		$result = array();
		if((int)$user_id>0){
			$select = $db->select()
						 ->from('user_and_group AS ug')
						 ->joinLeft('user_group as g', 'ug.user_group_id = g.id')
						 ->where('ug.group_default = 0')
						 ->where('ug.user_id = ?', $user_id, 1)
						 ->where('g.id != ?', $defaultGroupID, 1);
			$result = $db->fetchAll($select);
		}
		if(!empty($part)){
			if(count($result)>0){
				$cid = array();
				foreach ($result AS $key => $val){
					$cid[] = $val[$part];
				}
				$result = $cid;
			}else{
				$result = array();
			}
		}
		return $result;
	}
	
	public function getDefaultGroup($user_id,$part = null, $options = null){
		$db = $this->getAdapter();
		
		$result = array();
		if((int)$user_id>0){
			$select = $db->select()
						 ->from('user_and_group AS ug')
						 ->joinLeft('user_group as g', 'ug.user_group_id = g.id')
						 ->where('ug.group_default = 1')
						 ->where('ug.user_id = ?',$user_id,1);
			$result = $db->fetchRow($select);
		}
		if(!empty($part)){
			if(count($result)>0){
				$result = $result[$part];
			}else{
				$result = 0;
			}
		}
		return $result;
	}
	
	public function itemInSelect($arrParam = null,$options = null){
		//====================== Nested =======================		
		$exclude_id = !empty($arrParam['id'])?$arrParam['id']:0;
		$result = $this->listItem(0, 'all', $exclude_id);
		
		$view = new Zend_View();
		
		if($options == null){
			$result[0]['id'] = 0;
			$result[0]['name'] = $view->translate('-- Select a group --');
		}
		if($options == 'ext-group'){
			$result[0]['id'] = 0;
			$result[0]['name'] = $view->translate('-- None extend --');
		}
		return $result;
	}
	
	public function sortItem($arrParam = null,$options = null){
		if($options == null){
			if(!empty($arrParam['cid'])){
				$db = $this->getDefaultAdapter();
				$select = $db->select()
							->from($this->_name)
							->order('lft ASC');
				$result = $db->fetchAll($select);
				$data = array();
				foreach ($result as $v){
					$data[] = $v;
				}
				$orderArr = $arrParam['ordering'];
				$this->orderTree($data, $orderArr);
			}
		}
	}
	
	public function defaultGroup($arrParam = null,$options = null){
		if($options  == null){
			
			$default = ($arrParam['s'] == 0 )? 1:0;	
			$itemInfo = $this->getItem(array('id'=>(int)$arrParam['id']));
			if($default == 1){				
				$data = array('group_default' =>$default,);
				$where = "id = " . (int)$arrParam['id'];
				$this->update($data, $where);
			}else{
				if($arrParam['id'] > 0){
					$data = array('group_default' =>$default,);
					$where = "id = " . (int)$arrParam['id'];
					$this->update($data, $where);
				}
			}
		}
	}
	
	public function groupAcp($arrParam = null, $options = null){
		$groupAcp = ($arrParam['s'] == 0)?1:0;
		if($options == null){
			$data = array('group_acp' => $groupAcp);
			$where = 'id = ' . (int)$arrParam['id'];
			$this->update($data, $where);
		}
	}
	
	public function statusItem($arrParam = null,$options = null){
		if($options == null){
			$status = ($arrParam['s'] == 'active' )? 'inactive':'active';
			$fields = array('id');
			$children = $this->getChildrenNode($arrParam['id'],array('node'=>true,'fields'=>$fields));
			if(!empty($children)){
				foreach ($children as $val):
					if($val['group_default'] !=1 ){
						$data = array('status'=>$status);
						$where = 'id = ' . (int)$val['id'];
						$this->update($data, $where);
					}
				endforeach;
			}
		}
		
		if($options['task'] == 'multi'){
				
			$status = $arrParam['s'];
			if(count($arrParam['cid'])>0){
				foreach ($arrParam['cid'] as $val){
					$fields = array('id','group_default');
					$children = $this->getChildrenNode($val,array('node'=>true,'fields'=>$fields));
						
					if(!empty($children)){
						foreach ($children as $val):
							if($val['group_default'] !=1 ){
								$data = array('status'=>$status);
								$where = 'id = ' . (int)$val['id'];
								$this->update($data, $where);
							}
						endforeach;
					}
						
				}
			}
		}
	}
	public function deleteItem($arrParam = null,$options = null){
		$model = new Zendvn_Model_DeleteRecode();
		$model->group($arrParam,$options,$this);
	}
	
	public function getItem($arrParam = null,$options = null){
		if($options == null){
			if(!empty($arrParam['id'])){
				$result = $this->getNodeInfo($arrParam['id']);
			}
		}
		
		if($options['task'] == 'info'){
			$db = $this->getAdapter();
			$select = $db->select()
						->from('user_group AS g')
						->joinLeft('users AS u1', 'u1.id = g.created_by', array('u1.email AS created_by'))
						->joinLeft('users AS u2', 'u2.id = g.modified_by', array('u2.email AS modified_by'))
						->where('g.id = ?',$arrParam['id'],1);
			
			$result = $db->fetchRow($select);
		}
		return $result;
	}
	
	public function listItemAll($arrParam = null,$options = null){
		$select = $this->_sqlItem;
		$select->joinLeft('user_and_group AS uag', $this->_alias . '.id = uag.user_group_id', 'COUNT(uag.user_id) AS members')
				->group($this->_alias . '.id');
		
		$arrFilter = $arrParam['arrFilter'];
		if(!empty($arrFilter['col'])){
			$select->order($arrFilter['col'] . ' ' . $arrFilter['order']);			
		}

		if(!empty($arrFilter['status']) && $arrFilter['status'] != 'none'){
			$select->where('status = ?',$arrFilter['status']);
		}
		
		if(!empty($arrFilter['area']) && $arrFilter['area'] != 'none'){
			$select->where('area = ?',$arrFilter['area']);
		}
		
		if(!empty($arrFilter['keyword']) && !empty($arrFilter['searchField'])){
			$keyword = '%' . $arrFilter['keyword'] . '%';
			$select->where($arrFilter['searchField'] . ' LIKE ? ', $keyword);
		}
		$result = $this->listItem(0, 'all');
		$this->orderGroup($result);
		if(!empty($result)){
			foreach ($result as $k => $v){
				$result[$k]['ordering']	= $this->getNodeOrdering($v['parents'],$v['lft']);
			}
			
			//=============== Loai bỏ root ============
			foreach ($result as $k => $v){
				if($v['parents'] == 0){
					unset($result[$k]);
					break;
				}
			}
		}
		return $result;
	}	
	
	public function totalItem($arrParam = null,$options = null){
		$result = $this->totalNode() - 1;
		return $result;
		
	}
	
	public function saveItem($arrParam = null, $options = null){			
		$config = new Zendvn_Controller_Config(array('module'=>$arrParam['module'],
													 'fileConfig'=>'user-group.ini',
													 'section'=>'db'));
		if(!empty($arrParam['id'])){
			//=================== Edit Action ==================
			$data 			= array(
									'name' 			=> $arrParam['name'],
									'priority' 		=> $arrParam['priority'],
									'avatar' 		=> $arrParam['avatar'],
									'ranking' 		=> $arrParam['ranking'],
									'group_acp' 	=> $arrParam['group_acp'],
									'group_default' => $arrParam['group_default'],
									'status' 		=> $arrParam['status'],
									'modified' 		=> date('Y-m-d H:i:s'),
									'modified_by' 	=> $config->getConfig('modified_by')
								    );
			$id 			= $arrParam['id'];
			$newParentId 	= $arrParam['parents'];
			$this->updateNode($data, $id, $newParentId);
		}else{
			//==================== Add Action ==================
			$data = array(
							'name' 			=> $arrParam['name'],
							'priority' 		=> ($arrParam['priority']=='') ? $config->getConfig('priority'):$arrParam['priority'],
							'avatar' 		=> $arrParam['avatar'],
							'ranking' 		=> $arrParam['ranking'],
							'group_acp' 	=> $arrParam['group_acp'],
							'group_default' => $arrParam['group_default'],
							'status' 		=> $arrParam['status'],
							'created' 		=> date('Y-m-d H:i:s'),
							'created_by' 	=> $config->getConfig('created_by')
						 );
			$this->insertNode($data, $arrParam['parents'], $options);
		}
	}
}